﻿using Newtonsoft.Json;
using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.ThirdService.WeChat;
using YunSpace.Core;

namespace YunSpace.Application.MiniSite
{
    public class PaymentApp
    {
        public WxPayOutput WeChatPayment(string appId, string orderType, string orderId) {
            var orderApp = new SiteOrderApp();
            //var activityApp = new SiteActivityApp();

            var amount = ""; // orderEntity.F_OrderPrice.ToString();
            //var detail = string.Format("嗨空间：订单 {0}", orderId);
            var orderEntity = orderApp.GetForm(orderId);
            //if (!orderEntity.IsEmpty() && orderType == "3") {
            //    var activity = activityApp.GetForm(orderEntity.F_ActivityId);
            //    detail = activity.F_Title ?? "门票";
            //}
            if (!orderEntity.IsEmpty())
            {
                amount = orderEntity.F_OrderPrice.ToString();
            }
            
            // 根据类型来区分相关的场地或空间或活动（订单或预订单）

            return WeChatPayment(amount, orderId);
        }

        /// <summary>
        /// 微信支付
        /// </summary>
        /// <param name="amount">金额</param>
        /// <param name="detail">说明</param>
        private WxPayOutput WeChatPayment(string amount, string orderId) {

            if (amount.IsNullOrEmpty())
            {
                return new WxPayOutput
                {
                    Code = 50001,
                    Msg = "支付失败，订单金额为空"
                };
            }
            if (orderId.IsNullOrEmpty())
            {
                return new WxPayOutput
                {
                    Code = 50002,
                    Msg = "支付失败，订单号不能为空"
                };
            }
            var detail = string.Format("嗨空间：订单 {0}", orderId);

            var requestXml = WeiXinUtil.BuildRequest(amount, detail);
            var resultXml = WeiXinUtil.Post("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXml);

            var dic = WeiXinUtil.FromXml(resultXml);

            string returnCode;
            dic.TryGetValue("return_code", out returnCode);

            if (returnCode == "SUCCESS")
            {
                var prepay_id = WeiXinUtil.GetValueFromDic<string>(dic, "prepay_id");
                if (!string.IsNullOrEmpty(prepay_id))
                {
                    var payInfo = JsonConvert.DeserializeObject<WxPayModel>(WeiXinUtil.BuildAppPay(prepay_id));

                    return new WxPayOutput
                    {
                        Code = 0,
                        Msg = "成功",
                        Data = new WxPayEntity {
                            Appid = payInfo.appid,
                            Noncestr = payInfo.noncestr,
                            Package = payInfo.package,
                            Partnerid = payInfo.partnerid,
                            Prepayid = payInfo.prepayid,
                            Timestamp = payInfo.timestamp,
                            Sign = payInfo.sign
                        }
                    };
                }
                else
                {
                    return new WxPayOutput
                    {
                        Code = 40028,
                        Msg = "支付错误:" + WeiXinUtil.GetValueFromDic<string>(dic, "err_code_des")
                    };
                }
            }
            else
            {
                return new WxPayOutput
                {
                    Code = 50000,
                    Msg = "支付失败"
                };
            }
        }

        public bool WeChatCallback() {
            var context = HttpContext.Current;
            var request = context.Request;
            var verifyResult = false;
            var requestXml = WeiXinUtil.GetRequestXmlData(request);
            var dic = WeiXinUtil.FromXml(requestXml);
            var returnCode = WeiXinUtil.GetValueFromDic<string>(dic, "return_code");

            if (!string.IsNullOrEmpty(returnCode) && returnCode == "SUCCESS")//通讯成功
            {
                var result = WeiXinUtil.WePayNotifyValidation(dic);
                if (result)
                {
                    var transactionid = WeiXinUtil.GetValueFromDic<string>(dic, "transaction_id");

                    if (!string.IsNullOrEmpty(transactionid))
                    {
                        var queryXml = WeiXinUtil.BuildQueryRequest(transactionid, dic);
                        var queryResult = WeiXinUtil.Post("https://api.mch.weixin.qq.com/pay/orderquery", queryXml);
                        var queryReturnDic = WeiXinUtil.FromXml(queryResult);

                        if (WeiXinUtil.ValidatonQueryResult(queryReturnDic))//查询成功
                        {
                            verifyResult = true;
                            var status = WeiXinUtil.GetValueFromDic<string>(dic, "result_code");

                            if (!string.IsNullOrEmpty(status) && status == "SUCCESS")
                            {
                                //var order = new Order()
                                //{
                                //    OrderNumber = WeiXinUtil.GetValueFromDic<string>(dic, "out_trade_no"),
                                //    TransactionId = transactionid,
                                //    ProductPrice = WeiXinUtil.GetValueFromDic<decimal>(dic, "total_fee") / 100,
                                //    TradeType = WeiXinUtil.GetValueFromDic<string>(dic, "trade_type"),
                                //    BankType = WeiXinUtil.GetValueFromDic<string>(dic, "bank_type"),
                                //    PayDate = DateTime.Parse(WeiXinUtil.GetValueFromDic<string>(dic, "time_end")),
                                //    StatusId = 1,
                                //    IsPresent = false,
                                //    AddDate = DateTime.Now,
                                //    IsDelete = false
                                //};

                                //CURD.Add(order, ConfigHelper.WriteDB);

                                byte[] byData;
                                char[] charData;

                                try
                                {

                                    //创建一个临时文件夹
                                    string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "Temp");
                                    //判断目录是否存在
                                    if (!Directory.Exists(tempPath))
                                    {
                                        //如果不存在，创建它
                                        Directory.CreateDirectory(tempPath);
                                    }
                                    var path = Path.Combine(tempPath, "Temp.txt");
                                    FileStream aFile = new FileStream(path, FileMode.OpenOrCreate);

                                    var OrderNumber = WeiXinUtil.GetValueFromDic<string>(dic, "out_trade_no");
                                    var TransactionId = transactionid;
                                    var ProductPrice = WeiXinUtil.GetValueFromDic<decimal>(dic, "total_fee") / 100;
                                    var TradeType = WeiXinUtil.GetValueFromDic<string>(dic, "trade_type");
                                    var BankType = WeiXinUtil.GetValueFromDic<string>(dic, "bank_type");
                                    var PayDate = DateTime.Parse(WeiXinUtil.GetValueFromDic<string>(dic, "time_end"));
                                    charData = string.Format("== OrderNumber: {0} TransactionId:{1} ProductPrice:{2} TradeType:{3} BankType:{4} PayDate:{5}", 
                                        OrderNumber, 
                                        TransactionId, 
                                        ProductPrice,
                                        TradeType,
                                        BankType,
                                        PayDate).ToCharArray();
                                    byData = new byte[charData.Length];
                                    Encoder e = Encoding.UTF8.GetEncoder();
                                    e.GetBytes(charData, 0, charData.Length, byData, 0, true);

                                    // Move file pointer to beginning of file.
                                    aFile.Seek(0, SeekOrigin.Begin);
                                    aFile.Write(byData, 0, byData.Length);
                                }
                                catch (IOException ex)
                                {
                                    WeiXinUtil.BuildReturnXml("FAIL", "写入文件失败：" + ex.Message);
                                }

                                WeiXinUtil.BuildReturnXml("OK", "成功");
                            }
                        }
                        else
                            WeiXinUtil.BuildReturnXml("FAIL", "订单查询失败");
                    }
                    else
                        WeiXinUtil.BuildReturnXml("FAIL", "支付结果中微信订单号不存在");
                }
                else
                    WeiXinUtil.BuildReturnXml("FAIL", "签名失败");
            }
            else
            {
                string returnmsg;
                dic.TryGetValue("return_msg", out returnmsg);
                throw new Exception("异步通知错误：" + returnmsg);
            }

            return verifyResult;
        }

    }
}
